package com.brkj.download;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.brkj.model.DS_Course;
import com.brkj.util.ConstAnts;
import com.brkj.util.view.BaseActivity;

import com.brkj.util.view.BaseCoreActivity;
import com.dgl.sdk.util.FileCache;
import com.dgl.sdk.util.FileDownloader;
import com.dgl.sdk.util.Utils;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class CourseDLUnit {
	public final static int FINSHED = 100;
	public final static int UN_FINSHED = 0;
	
	private Context context;
	private int courseID;
	private Boolean  VideoDLState = false;
	
	private TextView progressTextView;
	private boolean DLState = false;

	private FinalHttp  fh;
	
	private FinalDb course_db;
	
	private FileDownloader videoFD;
	
	private String tempPecent = "";

    private String downlaodUrl;

	public  CourseDLUnit(Context context, int courseID){
		this.courseID = courseID;
		this.context = context;
        this.progressTextView = progressTextView;

		course_db = FinalDb.create(context,ConstAnts.BRKJ_DOWNLOAD_COURSE_DB);
		fh = new FinalHttp();
	}
	

	private void SaveCourseDLFinished(int courseId) {
		List<DS_Course> courseSaveList =
				course_db.findAllByWhere(DS_Course.class, " CourseID="+Integer.toString(courseId));
		
		if(courseSaveList.size()>0){
			courseSaveList.get(0).setIfFinish(FINSHED);
			course_db.update(courseSaveList.get(0));
		}
		
	}
	
	public void SaveCourseDLPecent(int courseId, String pecent) {
		if(!tempPecent.equals(pecent)){
			List<DS_Course> courseSaveList =
					course_db.findAllByWhere(DS_Course.class, " CourseID="+Integer.toString(courseId));
			if(courseSaveList.size()>0){
				courseSaveList.get(0).setPercent(pecent);
				course_db.update(courseSaveList.get(0));
			}
			tempPecent = pecent;
		}

	}

	private void DownloadContent(final String contentUrl, final int courseId, final boolean isZipFile) {
		if((contentUrl==null) || (contentUrl.equals(""))){
			VideoDLState = true;
			return;
		}
		


        FileCache fileCache =  new FileCache(context, ConstAnts.DOWNLOAD_COURSE__DIR);

        videoFD = new FileDownloader(context,contentUrl,fileCache.getFileCacheDir(),
                fileCache.urlToFileName(contentUrl),
                2,new FileDownloader.DownloadCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(int progress) {
                //每次都要去拿， 因为下载的过程中，不知什么时候就打开了下载页面，此时传过来进度更新视图
                TextView textView = (TextView) GetDownloadingView(courseId);
                if(textView!=null){
                    textView.setText(Integer.toString(progress)+ "%");
                }
                SaveCourseDLPecent(courseId, Integer.toString(progress));
            }

            @Override
            public void onComplete(final String filePath) {
                VideoDLState = true;

                SaveCourseDLFinished(courseId);

                CourseDownloader.Create(context).RemoveDownloadFinishedCourse(courseId);


                if(isZipFile){
                    File file  = new File(filePath);
                    File firlDir = new File(ConstAnts.DOWNLOAD_COURSE__DIR+file.getName()+"url");
                    firlDir.mkdirs();


                    Utils.Ectract(file.getAbsolutePath(), firlDir.getAbsolutePath());
                }

                Intent intent = new Intent();
                intent.setAction("com.brkj.dowanloadCourseFinish");
                intent.putExtra("courseID", courseID);
                context.sendBroadcast(intent);

            }

            @Override
            public void onError(String error) {

            }
        });
        videoFD.download();
//	    HttpHandler handler = fh.download(videoUrl, //这里是下载的路径
//	    		fileCache.GetVideoFilePath(videoUrl),
//	    		true,//true:断点续传 false:不断点续传（全新下载）
//	    	    new AjaxCallBack() {  
//	    	                @Override  
//	    	                public void onLoading(long count, long current) {  
//	    	                     textView.setText("下载进度："+current+"/"+count);  
//	    	                }  
//
//	    	                public void onSuccess(File t) {  
//	    	                    textView.setText(t==null?"null":t.getAbsoluteFile().toString());  
//	    	                }  
//
//	    	            });  
//		final VideoHandler myHandler = new VideoHandler(courseId);
//
//		Thread thread = new Thread(new Runnable() {
//			@Override
//			public void run() {
//				if (videoUrl != null) {
//					FileCache fileCache =  new FileCache(context);
//						try {
//							videoFD = new FileDownloader(context,
//									myHandler, videoUrl,
//									new File(fileCache.GetVideoFileDir()),
//									fileCache.urlToFileName(videoUrl),
//									2);
//
//
//							videoFD.download();
//
//
//						} catch (Exception e) {
//							myHandler.sendEmptyMessage(0);
//							e.printStackTrace();
//						}
//
//					}
//				}
//
//		});
//		thread.start();
		
		VideoDLState = false;
		
	}

    //给文件吗加上zip后缀
    private void changeFileName(File saveFile) {

        String oldname = saveFile.getAbsolutePath();
        String newname = oldname.concat(".zip");

        if (!oldname.equals(newname)) {
            File newFile = new File(newname);
            if (newFile.exists()) {
                System.out.println("您没有对文件名做修改，不能执行~");
            } else {
                saveFile.renameTo(newFile);
            }
        }
    }


	public int Download(DS_Course course  ) {
		int saveCourseResule = SaveCourse(course);

        downlaodUrl = getDownloadUrlByCourse(course);
		switch (saveCourseResule) {
		case 0:
			DownloadContent(downlaodUrl, course.getCourseID(),isZipFile(course));
			((BaseCoreActivity)context).showToast("已添加至下载列表");
			DLState = true;
			break;
		case 1:  //已下载过
			return 1;
		case 2: //已经在下载列表中
            DownloadContent(downlaodUrl, course.getCourseID(), isZipFile(course));
			((BaseCoreActivity)context).showToast("已在下载列表，正在下载中！");
			DLState = true;
			return 2;
		default:
			break;
		}

		return 0;
	}

    private boolean isZipFile(DS_Course course ) {
        if(course.getCourseType() == DS_Course.URL_COURSE){
            return true;
        }else{
            return  false;
        }
    }

    public int DownloadByID(int courseID, TextView progressTextView){

        this.progressTextView = progressTextView;

		List<DS_Course> courseSaveList =
				course_db.findAllByWhere(DS_Course.class, " CourseID=" + Integer.toString(courseID));

		if(courseSaveList.size() >0){
			if(courseSaveList.get(0).getIfFinish() == FINSHED){
				((BaseCoreActivity)context).showToast("您已下载此课程！");
				return 1;
			}else{
                downlaodUrl = getDownloadUrlByCourse(courseSaveList.get(0));
                DownloadContent(downlaodUrl, courseSaveList.get(0).getCourseID(), isZipFile(courseSaveList.get(0)));
				return 2;
			}
		}
		
		return 0;
	}
	
	public void StartDL(){
		if(!VideoDLState && !GetDLSate()){
			videoFD.setRun(true);
			try {
				videoFD.reDownLoad();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
				
		DLState = true;
	}
	
	public void PauseDL(){
		
		if(!VideoDLState){
			videoFD.setRun(false);
		}
		
		DLState = false;
	}
	
	public void DeleteDL(){
		if(videoFD != null){
			videoFD.delete();
		}else{  //没有下载实例， 新打开软件 就删除

			List<DS_Course> courseSaveList =
					course_db.findAllByWhere(DS_Course.class, " CourseID=" + Integer.toString(courseID));
			
			if(courseSaveList.size() >0){
                downlaodUrl = getDownloadUrlByCourse(courseSaveList.get(0));
                FileCache fileCache =  new FileCache(context, ConstAnts.DOWNLOAD_COURSE__DIR);
				videoFD = new FileDownloader(context,downlaodUrl,fileCache.getFileCacheDir(),
                        fileCache.urlToFileName(downlaodUrl),
                        2,null);
				
				videoFD.delete();
			}
			

		}

    }
	//true  在下载
	//false 不在下载
	public boolean GetDLSate(){
		return DLState;
	}
	
	public void SetDownloadingView(View view) {
		progressTextView = (TextView)view;
	}
	
	private View GetDownloadingView(int courseId) {
		
		return progressTextView;
	}

    /**
     *根据不同的课程类型 返回 要下载的地址。
     * @return
     */
    private String getDownloadUrlByCourse(DS_Course course){
        //dgltodo
//        return "http://118.192.9.79:85/kjzip.zip";
        switch (course.getCourseType()){
            case DS_Course.VIDEO_COURSE:
                return course.getVideoAdress();
            case DS_Course.SINGLE_IMG_COURSE:
                return course.getContent();
            case DS_Course.URL_COURSE:
                return course.getContent();
            default: return "";

        }
    }
	//return 1 : 已完成下载
	//return 2 : 已在下载列表中
	//return 0 : 正常开始下载
	private int SaveCourse(DS_Course course){
		List<DS_Course> courseSaveList =
				course_db.findAllByWhere(DS_Course.class, " CourseID='"+Integer.toString(course.getCourseID())+"'");
		

		if(courseSaveList.size() >0){
			if(courseSaveList.get(0).getIfFinish()== FINSHED){
				((BaseCoreActivity)context).showToast("您已下载此课程！");
				return 1;
			}else{
				((BaseCoreActivity)context).showToast("此课程正在下载！");
				return 2;
			}
		}else{
			
			course_db.save(course);

			Intent intent = new Intent();
			intent.setAction("com.brkj.newdowanloadCourse");
			context.sendBroadcast(intent);
			
			return 0;
		}
		
	}
	

}
